import React, { useState, useRef } from 'react';
import { Col, Row, Button } from 'antd';

function TrimImage() {
  const [fileData, setFileData] = useState({
    file: null,
    dataURL: '',
    scale: 1,
    startX: 0,
    startY: 0,
    dragging: false,
    lastX: 0,
    lastY: 0,
    avatarUrl: '',
  });
  const imageRef = useRef();
  const canvasRef = useRef();
  const avatarRef = useRef();

  const handleChange = (event) => {
    const file = event.target.files[0];
    const fileReader = new FileReader(file);
    fileReader.readAsDataURL(file);
    fileReader.onload = (e) => {
      setFileData({
        ...fileData,
        file,
        dataURL: e.target.result,
      });
      imageRef.current.onload = () => {
        drawImage(fileData);
      };
    };
  };

  const drawImage = ({ top = 0, left = 0, changedScale = 1 }) => {
    const image = imageRef.current;
    const canvas = canvasRef.current;
    const ctx = canvas.getContext('2d');
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    let imageWidth = image.width;
    let imageHeight = image.height;
    if (imageWidth > imageHeight) {
      const scale = canvas.width / imageWidth;
      imageWidth = canvas.width * changedScale;
      imageHeight = imageHeight * scale * changedScale;
    } else {
      const scale = canvas.height / imageHeight;
      imageHeight = canvas.height * changedScale;
      imageWidth = imageWidth.width * scale * changedScale;
    }
    const startX = (canvas.width - imageWidth) / 2 + left;
    const startY = (canvas.height - imageHeight) / 2 + top;
    ctx.drawImage(image, startX, startY, imageWidth, imageHeight);
  };

  const handleBig = () => {
    const newScale = fileData.scale + 0.1;
    const newFileData = {
      ...fileData,
      scale: newScale,
    };
    drawImage({ left: fileData.lastX, top: fileData.lastY, changedScale: newScale });
    setFileData(newFileData);
  };
  const handleSmall = () => {
    const newScale = fileData.scale - 0.1;
    const newFileData = {
      ...fileData,
      scale: newScale,
    };
    drawImage({ left: fileData.lastX, top: fileData.lastY, changedScale: newScale });
    setFileData(newFileData);
  };
  const handleTrim = () => {
    // drawImage({ left: fileData.lastX, top: fileData.lastY, changedScale: newScale})
    const canvas = canvasRef.current;
    const ctx = canvas.getContext('2d');
    const imageData = ctx.getImageData(100, 100, 100, 100);
    const avatarCanvas = document.createElement('canvas');
    avatarCanvas.width = 100;
    avatarCanvas.height = 100;
    const avatarCtx = avatarCanvas.getContext('2d');
    avatarCtx.putImageData(imageData, 0, 0);
    const dataURL = avatarCanvas.toDataURL();
    avatarRef.current.src = dataURL;
    setFileData((oldData) => ({ ...oldData, avatarUrl: dataURL }));
  };

  const handleMouseDown = (e) => {
    setFileData((oldData) => ({
      ...oldData,
      startX: e.clientX,
      startY: e.clientY,
      dragging: true,
    }));
  };

  const handleMouseMove = (e) => {
    if (fileData.dragging) {
      drawImage({
        left: e.clientX - fileData.startX + fileData.lastX,
        top: e.clientY - fileData.startY + fileData.lastY,
        changedScale: fileData.scale,
      });
    }
  };

  const handleMouseUp = (e) => {
    setFileData((oldData) => ({
      ...oldData,
      lastX: e.clientX - oldData.startX + oldData.lastX,
      lastY: e.clientY - oldData.startY + oldData.lastY,
      dragging: false,
    }));
  };

  const handleUpload = (e) => {
    const bytes = atob(fileData.avatarUrl.split(',')[1]);
    const byte = Buffer.from(fileData.avatarUrl.split(',')[1], 'base64');
    console.log(bytes, fileData.avatarUrl, byte);
    const arrayBuffer = new ArrayBuffer(bytes.length);
    const uInt8Array = new Uint8Array();
    for (let i = 0; i < bytes.length; i++) {
      uInt8Array[i] = bytes.charCodeAt[i];
      console.log(bytes.charCodeAt[i]);
    }
    const blob = new Blob([arrayBuffer], { type: 'image/png' });
    console.log('blob', blob, uInt8Array);
    const xhr = new XMLHttpRequest();
    const formData = new FormData();
    formData.append('avatar', blob);
    xhr.open('POST', 'http://127.0.0.1:8001/upload', true);
    xhr.send(formData);
  };

  return (
    <div>
      <Row gutter={16}>
        <Col span={8}>
          <input type="file" accept="image/*" onChange={handleChange} />
          {fileData.file && <img width={300} src={fileData.dataURL} ref={imageRef} />}
        </Col>
        <Col span={8}>
          {fileData.file && (
            <>
              <div
                style={{ position: 'relative' }}
                onMouseDown={handleMouseDown}
                onMouseMove={handleMouseMove}
                onMouseUp={handleMouseUp}
              >
                <canvas
                  ref={canvasRef}
                  width="300px"
                  height="300px"
                  style={{ border: '2px dashed blue' }}
                ></canvas>
                <div
                  style={{
                    width: 100,
                    height: 100,
                    backgroundColor: 'yellow',
                    opacity: 0.3,
                    position: 'absolute',
                    top: 100,
                    left: 100,
                  }}
                ></div>
              </div>
              <Button type="primary" ghost onClick={handleBig}>
                放大
              </Button>
              <Button danger ghost onClick={handleSmall}>
                缩小
              </Button>
              <Button type="primary" onClick={handleTrim}>
                剪辑
              </Button>
            </>
          )}
        </Col>
        <Col span={8}>
          <img ref={avatarRef} alt="" style={{ border: '2px dashed blue' }} />
          <Button type="primary" onClick={handleUpload}>
            上传
          </Button>
        </Col>
      </Row>
    </div>
  );
}

export default TrimImage;
